package OliveHTTP;

# Copyright (c) 2005, Shawn Boyette
# All rights reserved.
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, provided
# that the above copyright notice(s) and this permission notice appear
# in all copies of the Software and that both the above copyright
# notice(s) and this permission notice appear in supporting
# documentation.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE
# COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR
# ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY
# DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
# WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
# ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
# OF THIS SOFTWARE.
#
# Except as contained in this notice, the name of a copyright holder
# shall not be used in advertising or otherwise to promote the sale,
# use or other dealings in this Software without prior written
# authorization of the copyright holder.

require Exporter;
use warnings;
use strict;
use HTTP::Request;
use OliveMisc;

our @ISA       = qw(Exporter);
our @EXPORT    = qw( &fetchfeed );

sub fetchfeed {
    my ($cui,$nick,$force) = @_;
    $force = 0 unless (defined $force);

    my $c   = $cui->userdata->{c};
    my $ua = $cui->userdata->{ua};
    my $w   = $cui->userdata->{wins};
    my $frc = 0;
    my $feed = $c->{feeds}{$nick}{feed};
    my $feedfile  = $cui->userdata->{feeds} . "/$nick";
    my $res;
    my $msg;
    
    unless ($force) {
        # set up for checking feed status
        my $cachefile = $cui->userdata->{feeds} . "/$nick.cache";
        my %headers;
        $msg = "Checking ".$c->{feeds}{$nick}{disp}." status...";
        $w->{news}{ftr1}->text($msg . ' ' x ($w->{dim}[0] - length($msg)));
        $w->{news}{ftr1}->draw;        
        
        # read cached feed status if it exists
        if (-e $cachefile) {
            open (CACHE,"<",$cachefile) or die "Couldn't open: $!";
            %headers = ( If_None_Match => <CACHE>,
                         If_Last_Modified => <CACHE>
                );
            close CACHE;
            chomp $headers{If_None_Match} if $headers{If_None_Match};
            chomp $headers{If_Last_Modified} if $headers{If_Last_Modified};
        }
        
        # check feed status
        my $req = HTTP::Request->new( GET => $feed );
        $req->header(If_None_Match => $headers{If_None_Match});
        $req->header(If_Last_Modified => $headers{If_Last_Modified});
        $res = $ua->request($req);
        
        # store new headers for next time
        if ($res->is_success) {
            open (CACHE,">",$cachefile) or die "Couldn't open: $!";
            print CACHE $res->header('ETag'), "\n";
            print CACHE $res->header('Last-Modified'), "\n";
            close CACHE;
        }
    }

    if (($res && $res->code() eq '304') && $force == 0) {
        # 304 Not Modified; do nothing but mark feed as successfully checked
        $c->{feeds}{$nick}{last} = time();
        $c->write;
    } else {
        # no exception handlers match code; go get it
        $msg = "Fetching ".$c->{feeds}{$nick}{disp}."...";
        $w->{news}{ftr1}->text($msg . ' ' x ($w->{dim}[0] - length($msg)));
        $w->{news}{ftr1}->draw;        
        my $rc = $ua->get($feed, ':content_file' => $feedfile);
        if ($rc->is_success) {
            $c->{feeds}{$nick}{last} = time();
            $c->write;
            $frc = 1;
        } else {
            my $error = $rc->status_line;
            my $err = "There was a problem fetching ".$c->{feeds}{$nick}{disp}.":\n".
                "$error\n\nYou can try again by refrehing your feeds with 'r'.";
            errorbox($cui,$err);
        }
    }
    return $frc;
}

1;
